package main

import (
	config "gitee.com/woodpile/wgs.ths.config.go"
)

var (
	GlobalConfig = &Config{}
)

func init() {
	config.DefaultContext.RegisterRootConfig(GlobalConfig)
	config.DefaultContext.RegisterConfig("plugins[db]", &PluginDBConfig{})

	// config.GlobalRendererFile.ConfigFilepath("./config.yaml")
	config.GlobalRendererFile.ConfigFilepaths([]string{
		"./config.yaml",
		"./config.json",
	})

	config.GlobalRendererEnv.BindEnv("port", "P_PORT")
	config.GlobalRendererEnv.BindEnv("plugins[db].user", "P_DB_USER")

	config.GlobalRendererFlag.BindFlag("port", "", "port")
	config.GlobalRendererFlag.BindFlag("plugins[db].dbName", ".db", "database")
}

type Config struct {
	Address string `yaml:"address,omitempty" json:"address,omitempty"`
	Port    int    `yaml:"port,omitempty" json:"port,omitempty"`

	Logger *LoggerConfig `yaml:"logger,omitempty" json:"logger,omitempty"`

	Plugins map[string]interface{} `yaml:"plugins,omitempty" json:"plugins,omitempty"`
}

func (*Config) Name() string {
	return ""
}

func (*Config) ToDefault(cfg config.IConfigDefault) {
	ac := cfg.(*Config)
	if ac.Address == "" {
		ac.Address = "default_address"
	}
	if ac.Port == 0 {
		ac.Port = 8080
	}

	if ac.Logger == nil {
		ac.Logger = &LoggerConfig{}
	}
	// ac.Logger.ToDefault(ac.Logger)

	// ac.Plugins = map[string]config.Config{
	// 	"db": nil,
	// }
}

type LoggerConfig struct {
	Level int    `yaml:"level,omitempty" json:"level,omitempty"`
	Dir   string `yaml:"dir,omitempty" json:"dir,omitempty"`
}

func (*LoggerConfig) Name() string {
	return "logger"
}

func (*LoggerConfig) ToDefault(cfg config.IConfigDefault) {
	ac := cfg.(*LoggerConfig)
	if ac.Level == 0 {
		ac.Level = 2
	}
	if ac.Dir == "" {
		ac.Dir = "./logs"
	}
}

type PluginDBConfig struct {
	Host string `yaml:"host,omitempty" json:"host,omitempty"`
	User string `yaml:"user,omitempty" json:"user,omitempty"`
	Pass string `yaml:"pass,omitempty" json:"pass,omitempty"`

	DBName string `yaml:"db_name,omitempty" json:"db_name,omitempty"`
}

func (*PluginDBConfig) Name() string {
	return "db"
}

func (*PluginDBConfig) ToDefault(cfg config.IConfigDefault) {
	ac := cfg.(*PluginDBConfig)
	if ac.Host == "" {
		ac.Host = "localhost"
	}
	if ac.User == "" {
		ac.User = "root"
	}
	if ac.Pass == "" {
		ac.Pass = "123456"
	}
}
